<template>
  <div class="form-container">
    <div class="header">
      <div style="float: right">
        <el-button size="small" @click="close">取消</el-button>
        <el-button
          type="primary"
          size="small"
          :loading="loading"
          @click="onSubmit"
          >保存</el-button
        >
      </div>
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="refRuleForm"
        inline
        size="small"
        label-width="100px"
      >
        <el-form-item label="检查项目名称" prop="projectCode">
          <el-input v-model="ruleForm.projectCode"></el-input>
        </el-form-item>

        <!-- <el-form-item label="管理模块" prop="managementModule">
          <el-input v-model="ruleForm.managementModule"></el-input> 
        </el-form-item> -->

        <el-form-item label="所属部门" prop="deptName">
          <TreeSelect
            v-model="ruleForm.deptName"
            :options="deptTree"
            @change="changeDept"
            style="width: 100%"
          >
          </TreeSelect>
        </el-form-item>

        <el-form-item label="所属人" prop="userName">
          <el-input v-model="ruleForm.userName" readonly @click="onInnerOpen()">
          </el-input>
        </el-form-item>
      </el-form>
    </div>

    <div class="main">
      <VFormDesigner
        class="designer"
        ref="vfDesigner"
        :designer-config="designerConfig"
      ></VFormDesigner>
    </div>
    <TableSelect
      ref="userTableSelect"
      :queryApi="listUser"
      :options="[]"
      :rowKey="'userId'"
      rowLabel="nickName"
      @onConfirm="onUserConfirm"
      rowLabelText="用户昵称"
      :maxNum="1"
    >
      <template #formSlot="{ handleQuery, filterForm }">
        <el-col :span="8">
          <el-form-item label="部门名称">
            <el-input
              size="small"
              @change="handleQuery"
              v-model="filterForm.deptName"
              clearable
              style="width: 100%"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="用户名称">
            <el-input
              size="small"
              @change="handleQuery"
              v-model="filterForm.userName"
              clearable
              style="width: 100%"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
      </template>
      <template #tableSlot>
        <el-table-column
          label="部门"
          align="center"
          key="deptName"
          prop="dept.deptName"
        />
        <el-table-column
          label="用户名称"
          align="center"
          key="userName"
          prop="userName"
        />
        <el-table-column
          label="用户昵称"
          align="center"
          key="nickName"
          prop="nickName"
        />
      </template>
    </TableSelect>
  </div>
</template>

<script setup>
import { apis } from "@/api/znxj/jcxm.js";
import TableSelect from "@/components/tableSelect/index";
import { deptTreeSelect, listUser } from "@/api/system/user";
import { useRoute, useRouter } from "vue-router";
import { nextTick } from "vue";
const { proxy } = getCurrentInstance();

const route = useRoute();
const router = useRouter();
const designerConfig = ref({
  //是否显示语言切换菜单
  languageMenu: false,

  //是否显示GitHub、文档等外部链接
  externalLink: false,

  //是否显示表单模板
  formTemplates: false,

  //是否禁止修改唯一名称
  widgetNameReadonly: false,

  //是否显示组件事件属性折叠面板
  eventCollapse: true,

  //是否显示清空设计器按钮
  clearDesignerButton: true,

  //是否显示预览表单按钮
  previewFormButton: false,

  //是否显示导入JSON按钮
  importJsonButton: false,

  //是否显示导出JSON器按钮
  exportJsonButton: true,

  //是否显示导出代码按钮
  exportCodeButton: false,

  //是否显示生成SFC按钮
  generateSFCButton: false,

  //工具按钮栏最大宽度（单位px）
  //如新增按钮后不可见，请调大
  //如右侧空白区域过大，请调小
  toolbarMaxWidth: 260,

  //工具栏按钮最小宽度（单位px）
  //值必须小于toolbarMaxWidth
  toolbarMinWidth: 100,

  //表单设计器预设CSS代码
  presetCssCode: "",

  //表单设计器初始化自动清空内容
  /* 如设置为true，则刷新页面时也会清空设计器画布区域，慎用！*/
  resetFormJson: false,

  //设置自定义产品名称（仅Pro）
  productName: "",
  //设置自定义产品标题（仅Pro）
  productTitle: "",
});
const rules = {
  projectCode: [{ required: true, message: "请输入", trigger: "blur" }],
  deptName: [{ required: true, message: "请输入", trigger: "blur" }],
  userName: [{ required: true, message: "请输入", trigger: "blur" }],
};

const ruleForm = ref({});
const changeDept = (val, label) => {
  ruleForm.value.deptName = label;
  ruleForm.value.deptId = val;
};
const userTableSelect = ref();
const onInnerOpen = () => {
  const { userId, userName } = ruleForm.value;
  console.log(userId, userName);
  let values = (userId && (userId + "").split(",")) || [];
  let names = (userName && userName.split(",")) || [];

  userTableSelect.value.open(
    values.map((item, index) => ({
      value: values[index],
      label: names[index],
    }))
  );
};
const onUserConfirm = (data) => {
  const values = data.map((item) => item.value);
  const names = data.map((item) => item.label);
  ruleForm.value.userId = values.join(",");
  ruleForm.value.userName = names.join(",");
};
const refRuleForm = ref();
const vfDesigner = ref();
const close = () => {
  router.back();
};
const onSubmit = () => {
  refRuleForm.value.validate(async (valid) => {
    if (valid) {
      const fn = editData.value.id ? "update" : "add";
      apis[fn]({
        ...editData.value,
        ...ruleForm.value,
        formData: JSON.stringify(vfDesigner.value.getFormJson()),
      }).then(() => {
        proxy.$modal.msgSuccess("保存成功");
        setTimeout(close, 1000);
      });
    }
  });
};
const editData = ref({});
const deptTree = ref([]);
onMounted(() => {
  deptTreeSelect().then((response) => {
    deptTree.value = response.data;
  });
  nextTick().then(() => {
    const { row } = route.query;
    if (row) {
      ruleForm.value = JSON.parse(route.query.row);
      editData.value = JSON.parse(route.query.row);
      if (editData.value.formData) {
        vfDesigner.value.setFormJson(JSON.parse(editData.value.formData));
      }
    }
  });
});
</script>

<style lang="scss" scoped>
.form-container {
  .header {
    padding: 16px 16px 0;
    border-bottom: 1px solid #eee;
  }

  .main {
    height: calc(100vh - 67.5px);
    overflow: hidden;
  }
}

::v-deep .main-header {
  display: none;
}
</style>
